News robot

A simple and stupid news robot written in Python that takes some earthquake data (which we will just assume) and writes a news article based on that data.

1. Input data

Lets say we have these earthquake data that comes from somwehere.


In [ ]:
# Import datetime to use dates.
from datetime import *

In [ ]:
# The data comes in a dictionary (key-value pairs). Note that it looks just like JSON!
data = {
        "Richter": 7.5,
        "Latitud": 12,
        "Longitud": 12,
        "City": "Gothenburg",
        "Country": "Sweden",
        "Datetime": "2017-02-01 22:15:43"
       }

2. Check for errors

Don't assume that the data is always good. Create tests to make sure.


In [ ]:
# We start with the assumption that the data is news worthy.
IsNewsWorthy = True

# Are there errors in the data? 
if data["Richter"] > 100:
    # A earthquake with magnitue of 100 seems unlikely, so we ignore it.
    IsNewsWorthy = False

# We are only interested in earthquakes in Sweden.
if data["Country"] != "Sweden":
    IsNewsWorthy = False

3. Create text

Basically, it's just a lot of if-statements.

How to make the code easier to read:

  1. Don't nest if-statements inside each other too much. Use elif instead.
  2. Use multiline strings, with """ around them.
  3. Use .format on strings.
text = "My name is {0} and I am {1} years old"
text = text.format(Name, Age)

Which is the same as this:

text = "My name is " + Name + " and I am " + str(Age) + " years old"

In [ ]:
# If the earthquake is deemed news worthy, then create a journalistic text.
text = ""
if IsNewsWorthy:
    if (data["Richter"] > 6):
        # Text for large quake (6+).
        text = """BREAKING: Major earthquake in {0}
            
Today at {1} there was a severe earthquake in {2}, {3}, with a magnitude of {4} on the Richter scale.

"""
        text = text.format(data["City"], data["Datetime"], data["City"], data["Country"], data["Richter"])
    elif (data["Richter"] < 6 or data["Richter"] >= 3):
        # Text for medium quake (3-5).
        text = """Earthquake in {0}
            
Today at {1} there was a earthquake in {2}, {3}, with a magnitude of {4} on the Richter scale.

"""
        text = text.format(data["City"], data["Datetime"], data["City"], data["Country"], data["Richter"])

    # Add this at the end of all texts.
    text = text + "Published " + datetime.now().strftime("%Y-%m-%d %H:%M") + " by Ada the news robot"

In [ ]:
# Look at the text
print(text)

4. Save the results to a text file

Lets create a function that saves the text to a file.


In [ ]:
# Function to save the text to a file.
def savefile(filename, text):
    f = open(filename, mode="w")   # Open file for writing (w = writing, a = append, r = reading)
    f.write(text)
    f.close()

In [ ]:
# Only save as text file if there is some text.
if text != "":
    savefile("newsrobot-earthquake.txt", text)
    print("Text published!")
else:
    print("Text is not published.")

5. Present the results (read from text file)

Lets create a function that reads the text from the text file.


In [ ]:
# Function that reads text from a file.
def readfile(filename):
    f = open(filename, mode="r")   # Open file for reading (w = writing, a = append, r = reading)
    lines = f.read()
    f.close()
    return(lines)

In [ ]:
# Read the file created earlier by the news robot.
text = readfile("newsrobot-earthquake.txt")

In [ ]:
# Look at the text from the file.
print(text)

Exercise

Modify the code so that the robot writes a text based on these decisions:

  • Richter under 0.5 - Don't write anything.
  • Richter 0.5 to 2.0 - Small print on the news site.
  • Richter 2.0 to 4.0 - Front page.
  • Richter above 4.0 - Front page, breaking news.